<?php
	require_once $_SERVER['DOCUMENT_ROOT'] .
		'/SAGER/model/interfaces/IPlaceAccessDao.php';
	require_once $_SERVER['DOCUMENT_ROOT'] . '/SAGER/model/interfaces/IConnectionAccessDao.php';
	require_once $_SERVER['DOCUMENT_ROOT'] . '/SAGER/model/factory/ConnectionFactory.php';
	
	error_reporting (E_ALL ^ E_NOTICE);
	
	$debug = $_SESSION['debug'];

	class MySqlPlaceAccessDao implements IPlaceAccessDao {
   	 	/**
		 * Constructor of the place access dao
		 */
	 	public function __construct () {}
		
		/**
		 * Creates a place
		 */
		public function createPlace($place) {
			$type = $place -> getType();
			$name = $place -> getName();
			$fkIdPlace = $place -> getFkIdPlace();
			
			$GLOBALS['debug'] -> log($fkIdPlace, "fkIdPlace");
			
			$connection = ConnectionFactory :: getMySqlConnectionAccessDao();
			$conn = $connection -> openConnection();
			
			if (strcmp($type, 'PAIS') == 0)
				$query = "INSERT INTO PLACE (type, name, fk_id_place) VALUES ('$type', '$name', 
					NULL)";
					
			else if ($fkIdPlace)
				$query = "INSERT INTO PLACE (type, name, fk_id_place) VALUES ('$type', '$name', 
					$fkIdPlace)";
			
			else {
				$query = "INSERT INTO PLACE (type, name, fk_id_place) VALUES ('$type', '$name', 
					" . mysql_insert_id() . ")";
				$GLOBALS['debug'] -> log($query, "Query place");
			}
					
			$sentence = mysql_query($query, $conn);
			
			if ($sentence) {
				//$connection -> closeConnection($conn);
				return true;
			}
				
			$existingPlace = selectPlace($conn, $place);
			
			//$connection -> closeConnection($conn);
			
			return $existingPlace;
		}
		
		/**
		 * Selects a place
		 */
		public function selectPlace($conn, $place) {
			$type = $place -> getType();
			$name = $place -> getName();
			
			$query = "SELECT pk_id
					  FROM PLACE
					  WHERE type = '$type'
					  AND name = '$name'";
					  
			$sentence = mysql_query($query, $conn);
			
			$num_rows = mysql_num_rows($sentence);
			
			if ($num_rows != false) {
				$row = mysql_fetch_array($sentence);
				return $row['pk_id'];
			}
			
			return false;
		}
	 }


?>